package logic

import (
	"context"
	"github.com/pkg/errors"
	"mall/app/product/model"
	"mall/common/xerr"

	"mall/app/product/cmd/rpc/internal/svc"
	"mall/app/product/cmd/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCategoryBrandRelationLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddCategoryBrandRelationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCategoryBrandRelationLogic {
	return &AddCategoryBrandRelationLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// AddCategoryBrandRelation 新增品牌与分类关联关系, 考虑到冗余字段所以要先查再insert
func (l *AddCategoryBrandRelationLogic) AddCategoryBrandRelation(in *pb.AddCategoryBrandRelationReq) (*pb.EmptyResp, error) {
	// 根据brandId 去查brandName
	brand, err := l.svcCtx.BrandModel.FindOne(l.ctx, in.BrandId)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrorWithCode(xerr.DbError), "BrandModel.FindOne err: %v", err)
	}
	// 根据categoryId 去查categoryName
	category, err := l.svcCtx.CategoryModel.FindOne(l.ctx, in.CategoryId)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrorWithCode(xerr.DbError), "CategoryModel.FindOne err: %v", err)
	}
	// 数据插入
	_, err = l.svcCtx.CategoryBrandModel.Insert(l.ctx, &model.PmsCategoryBrandRelation{
		BrandId:     in.BrandId,
		CatelogId:   in.CategoryId,
		BrandName:   brand.Name,
		CatelogName: category.Name,
	})
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrorWithCode(xerr.DbError), "CategoryBrandModel.Insert err: %v", err)
	}
	return &pb.EmptyResp{}, nil
}
